package com.cw.auth.application.controller;

import com.alibaba.fastjson.JSON;
import com.cw.auth.application.convert.AuthPermissionDTOConverter;
import com.cw.auth.application.convert.AuthRolePermissionDTOConverter;
import com.cw.auth.application.dto.AuthPermissionDTO;
import com.cw.auth.application.dto.AuthRolePermissionDTO;
import com.cw.auth.common.entity.Result;
import com.cw.auth.domain.entity.AuthPermissionBO;
import com.cw.auth.domain.entity.AuthRolePermissionBO;
import com.cw.auth.domain.service.AuthPermissionDomainService;
import com.cw.auth.domain.service.AuthRolePermissionDomainService;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collections;

/**
 * 角色权限controller
 *
 * @Author:
 * @Date: 2024/4/28 19:06
 */

@RestController
@Slf4j
@RequestMapping("/rolePermission")
public class RolePermissionController {
    @Resource
    private AuthRolePermissionDomainService authRolePermissionDomainService;

    /**
     * @author: 江传文
     * @date: 2024/4/28 20:38
     * <p>
     * 新增角色权限关联关系
     */
    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody AuthRolePermissionDTO authRolePermissionDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("RolePermissionController.add.dto:{}", JSON.toJSONString(authRolePermissionDTO));
            }
            // 检查传入的字符串是否为 null、空字符串或者只包含空白字符（空格、制表符、换行符等）
            Preconditions.checkArgument(!CollectionUtils.isEmpty(authRolePermissionDTO.getPermissionIdList()),"权限关联不能为空");
            Preconditions.checkNotNull(authRolePermissionDTO.getRoleId(),"角色不能为空!");
            // (DTO -> BO)
            AuthRolePermissionBO authRolePermissionBO = AuthRolePermissionDTOConverter.INSTANCE
                    .convertDtoToBO(authRolePermissionDTO);

            return Result.ok(authRolePermissionDomainService.add(authRolePermissionBO));
        } catch (Exception e) {
            log.error("RolePermissionController.add.error:{}", e.getMessage(), e);
            return Result.fail("新增角色权限失败");
        }
    }

}
